package com.cvs.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.cvs.model.DaysEntity;
import com.cvs.model.EventsEntity;
import com.cvs.model.UserEntity;
import com.cvs.security.SecurityUtilities;
import com.cvs.services.ChmService;

@Controller
public class BookController {

	@Autowired
	private ChmService controllerService;

	public ChmService getControllerService() {
		return controllerService;
	}

	public void setControllerService(ChmService controllerService) {
		this.controllerService = controllerService;
	}

	@RequestMapping(value = "/book", method = RequestMethod.GET)
	public String getBookPage(HttpServletRequest req, ModelMap model,
			HttpSession session, HttpServletResponse resp) throws IOException,
			ParseException {

		UserEntity user = new UserEntity();
		
		SecurityUtilities sec = new SecurityUtilities();

		String username = sec.getLoggedInUserName();
		user = controllerService.searchDatabaseForUsername(username);
		
		List<EventsEntity> events = new ArrayList<EventsEntity>();
		events = controllerService.getEvents();
		
		model.addAttribute("event",events);
		model.addAttribute("user", user);
		return "book";

	}

	@RequestMapping(value = "/bookDate", method = RequestMethod.POST)
	public String createNewUser(HttpServletRequest req, ModelMap model,
			HttpSession session, HttpServletResponse resp) throws IOException,
			ParseException {
		DaysEntity day = new DaysEntity();
		UserEntity user = new UserEntity();
		DateFormat formatter = new SimpleDateFormat("yyyy-M-d");
		int allocation = 0;
		
		
		
		// get logged in user
		SecurityUtilities sec = new SecurityUtilities();
		String User = sec.getLoggedInUserName();
		user = controllerService.searchDatabaseForUsername(User);

		// format date so that it can be inserted to database
		String dateInString = req.getParameter("mydate");

		try {
			Date parsed = formatter.parse(dateInString.trim());
			day.setStartDate(parsed);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		String endDateInString = req.getParameter("todate");

		try {
			Date parse = formatter.parse(endDateInString.trim());
			day.setEndDate(parse);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		// calculate difference between dates
		String dateStart = req.getParameter("mydate");
		String dateEnd = req.getParameter("todate");

		SimpleDateFormat format = new SimpleDateFormat("yyyy-M-d");
		System.out.println(dateStart);
		System.out.println(dateEnd);
		Date d1 = null;
		Date d2 = null;
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();

		try {
			d1 = format.parse(dateStart);
			d2 = format.parse(dateEnd);

			c1.setTime(d1);
			c2.setTime(d2);
			
			int numberofdays =0;
			
			while(c1.before(c2)){
				if((Calendar.SATURDAY != c1.get(Calendar.DAY_OF_WEEK))
				           &&(Calendar.SUNDAY != c1.get(Calendar.DAY_OF_WEEK))){
		            numberofdays++;
		            c1.add(Calendar.DATE,1);
		        }else {
		            c1.add(Calendar.DATE,1);
		        }
		    }
		    numberofdays = numberofdays + 1;

			System.out.print(numberofdays + " days, ");

			allocation = user.getAllocation();
			System.out.println(allocation);
			if (numberofdays > 0) {
				allocation = allocation - numberofdays;
			}
			System.out.println(allocation);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String error;
		user.setAllocation(allocation);
		day.setDate(new Date());
		
		System.out.println("date one" + c1 + "date 2" + c2);
		day.setAccepted("false");
		day.setUsername(User);
		if (allocation >= 1 ) {
			controllerService.createHolidayRecord(day);

			controllerService.updateUserAllocation(User, allocation);
		} else{
			error = "You have made an error in your request. Ensure you have selected a date after the start date and have sufficient allocation";
			model.addAttribute("error", error);
			System.out.println("no holiday allocation remaining!");}
		return "book";
	}
	
}
